<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      #min {
        width: 450px;
        height: 450px;
        margin: 200px 0 0 200px;
        border: 1px soild red;
        position: relative;
      }

      #max {
        position: absolute;
        left: 460px;
        top: 0;
        width: 550px;
        height: 550px;
        overflow: hidden;
        border: 1px solid #ccc;
        display: none;
      }

      #max img {
        position: absolute;
        left: 0;
        top: 0;
      }

      #mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 255px;
        height: 225px;
        background-color: rgba(255, 255, 0, 0.4);
        display: none;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="min">
      <img src="./img/min.jpg" alt="" />
      <div id="mask"></div>
    </div>
    <div id="max">
      <img src="./img/max.jpg" alt="" id="image" />
    </div>
    <script>
      //封装获取id元素
      function $(str) {
        return document.getElementById(str);
      }
      //移入效果
      $("min").onmousemove = function (ev) {
        var ev = ev || window.event;
        ev.preventDefault();
        //显示隐藏元素
        $("mask").style.display = "block";
        $("max").style.display = "none";
        //获取鼠标相对左边盒子的位置(x,y)
        var disx = ev.clientX - $("min").offsetLeft;
        var disy = ev.clientY - $("min").offsetTop;
        //蒙版的中心位置
        var x = disx - $("mask").offsetWidth / 2;
        var y = disy - $("mask").offsetHeight / 2;
        //设置蒙版的运动范围
        var maxW = $("min").offsetWidth - $("mask").offsetWidth;
        var maxH = $("min").offsetHeight - $("mask").offsetHeight;
        //判断蒙版移动范围的临界值
        if (x > maxW) {
          //水平位置的判断
          x = maxW;
        } else if (x < 0) {
          x = 0;
        }
        if (y > maxH) {
          //垂直位置的判断
          y = maxH;
        } else if (y < 0) {
          y = 0;
        }
        //蒙版赋值
        $("mask").style.top = y + "px";
        $("mask").style.left = x + "px";
        //求出蒙版移动位置对应大图片移动区域的比例
        var secx = x / maxW;
        var secy = y / maxH;
        console.log(secx + ":" + secy);
        //大盒子的滚动条偏移量 = 引动区域的比例*(大图片的宽度 - 大盒子的宽度)
        $("max").scrollLeft =
          secx * ($("image").offsetWidth - $("max").clientWidth);
        $("max").scrollTop =
          secy * ($("image").offsetHeight - $("max").clientHeight);
        //鼠标移出
        $("min").onmouseleave = function () {
          $("mask").style.display = "none";
          $("max").style.display = "none";
        };
      };
    </script>
  </body>
</html>
